package com.example.caoben_back.contoller;

import com.example.caoben_back.entity.vo.Result;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/agent/service")
@Slf4j
public class AgentController {

    @Value("${agent.image.upload.path:src/main/resources/agentImage}")
    private String uploadPath;

    @PostConstruct
    public void init() {
        // 确保上传目录存在
        try {
            Path directory = Paths.get(uploadPath);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }
        } catch (IOException e) {
            log.error("创建上传目录失败", e);
        }
    }

    /**
     * 文件上传接口
     *
     * @param file 上传的文件
     * @return 上传结果，包含文件名和访问URL
     */
    @PostMapping("/upload")
    public Result<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("文件为空");
        }

        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.fail("文件名为空");
            }

            // 生成唯一文件名
            String fileExtension = "";
            int lastIndex = originalFilename.lastIndexOf('.');
            if (lastIndex > 0) {
                fileExtension = originalFilename.substring(lastIndex);
            }
            String uniqueFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileExtension;

            // 构建保存路径
            File destFile = new File(uploadPath, uniqueFileName);

            // 保存文件
            file.transferTo(destFile);

            // 返回结果
            String fileUrl = "/agentImage/" + uniqueFileName;
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("fileName", uniqueFileName);
            resultMap.put("url", fileUrl);

            log.info("文件上传成功，文件名: {}, 访问URL: {}", uniqueFileName, fileUrl);
            return Result.success(resultMap);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }
}